package com.future.lock.mall.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.future.lock.R;
import com.future.lock.common.Constants;
import com.future.lock.common.MyApp;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.common.http.response.DefaultHttpResponse;
import com.future.lock.mall.entity.beans.GoodDetailsBean;
import com.future.lock.mall.entity.beans.InstallAreaDescBean;
import com.future.lock.mall.entity.beans.InstallFeeBean;
import com.future.lock.mall.entity.beans.SelectDistrictBean;
import com.future.lock.mall.entity.beans.ShareInfoBean;
import com.future.lock.mall.entity.response.BaseDataResponse;
import com.future.lock.mall.utils.Utils;
import com.future.lock.mall.view.ImageViewSelectorDialog;
import com.future.lock.mall.view.InstallFeeDescDialog;
import com.future.lock.mall.view.PayMethodDialog;
import com.future.lock.mall.widgets.NoticePopupDialog;
import com.future.lock.me.activity.LoginActivity;
import com.future.lock.me.order.OrderDetailsActivity;
import com.future.lock.me.order.utils.JSONUtil;
import com.future.lock.pay.PayActivity;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citylist.utils.CityListLoader;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.yzh.modaldialog.dialog.impl.SelectorDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.SwitchView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrderConfirmActivity extends PayActivity {

    public static final String ORDER_ID = "order_id";
    public static final String GOODS_BEAN_KEY = "good_bean";
    private static final int CODE_CALL_KEFU_PERM = 100;

    @BindView(R.id.shareBonusArea)
    View shareBonusArea;

    @BindView(R.id.shareTextView)
    TextView shareTextView;

    @BindView(R.id.clickToShareTextView)
    TextView clickToShareTextView;

    @BindView(R.id.userTextView)
    EditText userTextView;

    @BindView(R.id.mobileTextView)
    EditText mobileTextView;

    @BindView(R.id.districtTextView)
    TextView districtTextView;

    @BindView(R.id.addressTextView)
    EditText addressTextView;

    @BindView(R.id.icon)
    ImageView icon;

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.installCheckBox)
    SwitchView installCheckBox;

    @BindView(R.id.addFeeCheckBox)
    SwitchView addFeeCheckBox;

    @BindView(R.id.feeCaption)
    TextView feeCaption;

    @BindView(R.id.feeTextView)
    TextView feeTextView;

    @BindView(R.id.installFeelayout)
    View installFeelayout;

    @BindView(R.id.installFeeTextView)
    TextView installFeeTextView;

    @BindView(R.id.addFeelayout)
    View addFeelayout;

    @BindView(R.id.addFeeDescLayout)
    View addFeeDescLayout;

    @BindView(R.id.addFeeTextView)
    TextView addFeeTextView;

    @BindView(R.id.discountLayout)
    View discountLayout;

    @BindView(R.id.discountCaption)
    TextView discountCaption;

    @BindView(R.id.discountTextView)
    TextView discountTextView;

    @BindView(R.id.price)
    TextView price;

    @BindView(R.id.operateButton)
    CheckedTextView operateButton;


    GoodDetailsBean goodDetailsBean;
    boolean mustInstall = false;
    boolean supportInstall = false;
    Double installFee = 0d;
    private SelectDistrictBean selectDistrictBean;
    private double shareBunus = 0d;
    private double addedFee = 0d;
    private boolean shared = false;

    private String orderNo = "";
    private int dialogCount = 0;

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_confirm);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        setTitle("确认订单");
        setTitleRight("客服", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadingDialog();
                HttpUtils.getHttpApi()
                        .getKefudianhua()
                        .enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {
                                try {
                                    dissmissLoadingDialog();
                                    final String phone = new JSONObject(response.body()).optString("data");
                                    if (!TextUtils.isEmpty(phone)) {
                                        tryToCallKefu(phone);
                                    }
                                }
                                catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(Call<String> call, Throwable t) {
                                dissmissLoadingDialog();
                                toast("获取客服电话失败, 请稍后重试!");
                            }
                        });
            }
        });
        CityPickerView.getInstance()
                .init(this);
        CityListLoader.getInstance()
                .loadProData(this);

        setupUisByOrderDetailsBean(goodDetailsBean);
        setupInstallFee(null);
        setupAddedFee();
        setupShareInfo();
        setupUserAddress();
    }

    private void setupUserAddress() {
        showSmartLoadingDialog();
        HttpUtils.getHttpApi()
                .getAddress(MyApp.getUserToken())
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        try {
                            dismissSmartLoadingDialog();
                            BaseDataResponse<SelectDistrictBean> response1 = new BaseDataResponse<>(SelectDistrictBean.class);
                            response1.parse(response.body());
                            selectDistrictBean = response1.data;
                            if (selectDistrictBean != null) {
                                userTextView.setText(selectDistrictBean.getConsignee());
                                mobileTextView.setText(selectDistrictBean.getPhone());
                                districtTextView.setText(selectDistrictBean.getProvince_name() + " " + selectDistrictBean.getCity_name() + " " + selectDistrictBean.getCounty_name());
                                addressTextView.setText(selectDistrictBean.getAddress());
                            }
                            updateInstallFee();
                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        dismissSmartLoadingDialog();
                    }
                });
    }

    private void setupAddedFee() {
        showSmartLoadingDialog();
        HttpUtils.getHttpApi()
                .getAddedFee()
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        try {
                            dismissSmartLoadingDialog();
                            addedFee = JSONUtil.getDoubleRecursive(new JSONObject(response.body()), "added_fee");
                            addFeeDescLayout.setVisibility(addedFee > 0 ? View.VISIBLE : View.GONE);
                            addFeeCheckBox.setEnabled(addedFee > 0);
                            updateTotalPrice();
                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        dismissSmartLoadingDialog();
                    }
                });

        this.addFeeCheckBox.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView switchView) {
                switchView.toggleSwitch(true);
                addFeelayout.setVisibility(View.VISIBLE);
                addFeeTextView.setText("+" + getPriceStr((float) addedFee));
                updateTotalPrice();
            }

            @Override
            public void toggleToOff(SwitchView switchView) {
                switchView.toggleSwitch(false);
                addFeelayout.setVisibility(View.GONE);
                addFeeTextView.setText(getPriceStr((float) 0));
                updateTotalPrice();
            }
        });
    }

    /**
     * 设置分享
     */
    private void setupShareInfo() {
        showSmartLoadingDialog();
        HttpUtils.getHttpApi()
                .getShareBunusInfo()
                .enqueue(new Callback<String>() {

                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        dismissSmartLoadingDialog();
                        DefaultHttpResponse defaultHttpResponse = new DefaultHttpResponse() {
                            @Override
                            protected void parseData(String dataString) {
                                try {
                                    shareBunus = JSONUtil.getDoubleRecursive(new JSONObject(dataString), "lijian");
                                    if (shareBonusArea != null) {
                                        shareBonusArea.setVisibility(shareBunus != 0 ? View.VISIBLE : View.GONE);
                                        shareTextView.setText(String.format("分享立减%.2f元", shareBunus));
                                    }
                                }
                                catch (JSONException e) {
                                    e.printStackTrace();
                                    toast("获取分享立减金额失败！");
                                }
                            }
                        };
                        defaultHttpResponse.parse(response.body());
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        toast(t.getMessage());
                        dismissSmartLoadingDialog();
                    }
                });
    }

    /**
     * 给客服电话
     *
     * @param phone
     */
    private void tryToCallKefu(String phone) {
        if (Build.VERSION.SDK_INT < 23) {
            Utils.callPhones(OrderConfirmActivity.this, phone);
            return;
        }

        if (ActivityCompat.checkSelfPermission(OrderConfirmActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(OrderConfirmActivity.this, new String[]{Manifest.permission.CALL_PHONE}, CODE_CALL_KEFU_PERM);
        }
        else {
            Utils.callPhones(OrderConfirmActivity.this, phone);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == CODE_CALL_KEFU_PERM) {
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    toast("程序需要拨打电话权限才能给客服打电话!");
                }
            }
        }
    }

    @OnClick({R.id.addFeeInfoCaption, R.id.addFeeInfoIcon})
    protected void addFeeInfoClicked() {
        showSmartLoadingDialog();
        HttpUtils.getHttpApi()
                .getZengzhifuwu()
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        try {
                            dismissSmartLoadingDialog();
                            final String content = new JSONObject(response.body()).optString("data");
                            NoticePopupDialog dialog = new NoticePopupDialog(OrderConfirmActivity.this);
                            dialog.setTitle("增值服务说明");
                            dialog.setContent(Html.fromHtml(content));
                            dialog.setConfirm("知道了");
                            dialog.doModal();
                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                            toast("获取增值服务说明失败, 请稍后再试!");
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        dismissSmartLoadingDialog();
                        toast("获取增值服务说明失败, 请稍后再试!");
                    }
                });


    }

    @OnClick({R.id.installFeeInfoCaption, R.id.installFeeInfoIcon})
    protected void installFeeInfoClicked() {
        showSmartLoadingDialog();
        HttpUtils.getHttpApi()
                .getInstallAreaDesc()
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        dismissSmartLoadingDialog();
                        BaseDataResponse<InstallAreaDescBean> response1 = new BaseDataResponse<InstallAreaDescBean>(InstallAreaDescBean.class);
                        response1.parse(response.body());
                        InstallAreaDescBean installAreaDescBean = response1.data;
                        if (installAreaDescBean != null) {
                            showInstallDescDialog(installAreaDescBean);
                        }
                        else {
                            toast("获取安装区域说明失败, 请稍后再试!");
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        toast("获取安装区域说明失败, 请稍后再试!");
                        dismissSmartLoadingDialog();
                    }
                });
    }

    private void showInstallDescDialog(InstallAreaDescBean installAreaDescBean) {
        InstallFeeDescDialog descDialog = new InstallFeeDescDialog(this, installAreaDescBean);
        descDialog.doModal();
    }


    @OnClick(R.id.districtTextView)
    protected void onDistrictTextView() {
        hideCurrentSoftInputMethod();

        CityConfig.Builder builder = new CityConfig.Builder(this).title("选择城市")//标题
                .titleTextSize(17)//标题文字大小
                .titleTextColor("#000000")//标题文字颜色
                .titleBackgroundColor("#F7F7F7")//标题栏背景色
                .confirTextColor("#007AFF")//确认按钮文字颜色
                .confirmText("确认")//确认按钮文字
                .confirmTextSize(15)//确认按钮文字大小
                .cancelTextColor("#007AFF")//取消按钮文字颜色
                .cancelText("取消")//取消按钮文字
                .cancelTextSize(15)//取消按钮文字大小
                .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类，只显示省份一级，显示省市两级还是显示省市区三级
                .showBackground(false)//是否显示半透明背景
                .visibleItemsCount(7)//显示item的数量
                .provinceCyclic(false)//省份滚轮是否可以循环滚动
                .cityCyclic(false)//城市滚轮是否可以循环滚动
                .districtCyclic(false)//区县滚轮是否循环滚动
                .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_city_name_tv);

        if (selectDistrictBean != null) {
            builder.province(selectDistrictBean.getProvince_name())
                    .city(selectDistrictBean.getCity_name())
                    .district(selectDistrictBean.getCounty_name());
        }

        CityPickerView.getInstance()
                .setConfig(builder.build());

        //监听选择点击事件及返回结果
        CityPickerView.getInstance()
                .setOnCityItemClickListener(new OnCityItemClickListener() {
                    @Override
                    public void onSelected(com.lljjcoder.bean.ProvinceBean province, com.lljjcoder.bean.CityBean city, DistrictBean district) {
                        selectDistrictBean = new SelectDistrictBean();
                        selectDistrictBean.setProvince(province.getId());
                        selectDistrictBean.setCity(city.getId());
                        selectDistrictBean.setCounty(district.getId());
                        selectDistrictBean.setProvince_name(province.getName());
                        selectDistrictBean.setCity_name(city.getName());
                        selectDistrictBean.setCounty_name(district.getName());
                        districtTextView.setText(province.getName() + " " + city.getName() + " " + district.getName());
                        updateInstallFee();
                    }
                });

        //显示
        CityPickerView.getInstance()
                .showCityPicker(this);
    }

    /**
     * update the install fee by current selected disctrict bean
     */
    private void updateInstallFee() {
        if (selectDistrictBean != null) {
            showLoadingDialog();
            HttpUtils.getHttpApi()
                    .getInstallFee(selectDistrictBean.getCounty())
                    .enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            dissmissLoadingDialog();
                            BaseDataResponse<InstallFeeBean> baseDataResponse = new BaseDataResponse(InstallFeeBean.class);
                            baseDataResponse.parse(response.body());
                            setupInstallFee(baseDataResponse.data);
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                            dissmissLoadingDialog();
                            toast("获取城市安装费信息失败, 请稍后再试!");
                        }
                    });
        }
    }

    private void setupInstallFee(final InstallFeeBean data) {
        if (data == null) {
            mustInstall = false;
            supportInstall = false;
            installFee = 0d;
            installCheckBox.setOpened(false);
            installCheckBox.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
                @Override
                public void toggleToOn(SwitchView switchView) {
                    toast("请先选择您所在地区!");
                }

                @Override
                public void toggleToOff(SwitchView switchView) {
                    toast("请先选择您所在地区!");
                }
            });
            installCheckBox.setEnabled(false);
            installFeelayout.setVisibility(View.GONE);
        }
        else {
            supportInstall = data.isIs_install();
            mustInstall = data.isIs_install() && data.isIs_force();
            installFee = data.getInstall_fee();
            installFeelayout.setVisibility(!mustInstall || !supportInstall ? View.GONE : View.VISIBLE);
            installFeeTextView.setText(String.format("+¥%.2f", installFee));
            installCheckBox.setOpened(data.isIs_install());
            installCheckBox.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
                @Override
                public void toggleToOn(SwitchView switchView) {
                    if (!supportInstall) {
                        switchView.setOpened(false);
                        toast("您所在区域暂不支持安装服务!");
                        return;
                    }

                    switchView.toggleSwitch(true);
                    updateInstallFeeLayout(true);
                    updateTotalPrice();
                }

                @Override
                public void toggleToOff(SwitchView switchView) {
                    if (mustInstall) {
                        switchView.setOpened(true);
                        toast("您所在区域为强制安装区域!");
                        return;
                    }

                    switchView.toggleSwitch(false);
                    updateInstallFeeLayout(false);
                    updateTotalPrice();
                }
            });
        }

        updateTotalPrice();
        updateInstallFeeLayout(supportInstall);
    }

    private void updateInstallFeeLayout(boolean show) {
        installFeelayout.setVisibility(show ? View.VISIBLE : View.GONE);
        installFeeTextView.setText(String.format("+¥%.2f", (show ? installFee : 0f)));
    }

    private void setupUisByOrderDetailsBean(GoodDetailsBean goodDetailsBean) {
        if (goodDetailsBean != null && this.icon != null) {
            this.title.setText(goodDetailsBean.getGoods_name());
            this.price.setText(getPriceStr(goodDetailsBean.getPrice()));
            this.feeTextView.setText(getPriceStr(goodDetailsBean.getPrice()));
            this.operateButton.setChecked(true);
            this.operateButton.setText("提交订单");
            updateTotalPrice();

            Glide.with(this)
                    .load(goodDetailsBean.getHead_img())
                    .placeholder(R.drawable.ssdk_oks_classic_telegram)
                    .dontAnimate()
                    .into(icon);
        }
    }

    protected void updateTotalPrice() {
        if (goodDetailsBean != null) {
            float total = 0f;
            total += goodDetailsBean.getPrice();
            total += getInstallFee();
            total += getAddedFee();
            total -= getSharedDiscount();
            this.price.setText(getPriceStr(total));
        }
    }

    /**
     * 获取当前订单安装费
     *
     * @return
     */
    private float getInstallFee() {
        return installCheckBox.isOpened() ? installFee.floatValue() : 0f;
    }

    /**
     * 获取当前订单的增值费
     *
     * @return
     */
    private float getAddedFee() {
        return addFeeCheckBox.isOpened() ? (float) addedFee : 0f;
    }

    /**
     * 获取当前订单的分享折扣
     *
     * @return
     */
    private float getSharedDiscount() {
        return shared ? (float) shareBunus : 0f;
    }

    @OnClick(R.id.clickToShareTextView)
    protected void onShareClicked() {
        showSmartLoadingDialog();
        HttpUtils.getHttpApi()
                .getShareInfo()
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        dismissSmartLoadingDialog();
                        BaseDataResponse<ShareInfoBean> bsp = new BaseDataResponse<ShareInfoBean>(ShareInfoBean.class);
                        bsp.parse(response.body());
                        if (bsp.data != null) {
                            shareTo(bsp.data);
                        }

                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        dismissSmartLoadingDialog();
                        toast("获取分享信息失败, 请稍后再试!");
                    }
                });


    }

    /**
     * 分享
     *
     * @param shareInfo
     */
    protected void shareTo(ShareInfoBean shareInfo) {
        if (shareInfo == null) {
            return;
        }

        Platform.ShareParams paramsToShare = new Platform.ShareParams();
        String imgUrl = shareInfo.getImg_url();
        if (!TextUtils.isEmpty(imgUrl) && !imgUrl.startsWith("http")) {
            imgUrl = Constants.BASE_URL + imgUrl;
        }
        final String url = shareInfo.getUrl();
        final String title = shareInfo.getTitle();
        final String content = shareInfo.getSubtitle();

        SelectorDialog dialog = new ImageViewSelectorDialog(this, R.layout.dialog_share_selector);
        dialog.setCancelOnClickOutside(false);
        final int choice = dialog.doModal();
        String platformStr = "";
        switch (choice) {
            case R.id.shareToPyq:
                platformStr = WechatMoments.NAME;
                paramsToShare.setTitle(title);
                paramsToShare.setUrl(url);
                paramsToShare.setImageUrl(imgUrl);
                paramsToShare.setText(content);
                paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                break;
            case R.id.shareToWx:
                platformStr = Wechat.NAME;
                paramsToShare.setTitle(title);
                paramsToShare.setUrl(url);
                paramsToShare.setImageUrl(imgUrl);
                paramsToShare.setText(content);
                paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                break;
            case R.id.shareToQq:
                platformStr = QQ.NAME;
                paramsToShare.setTitle(title);
                paramsToShare.setTitleUrl(url);
                paramsToShare.setImageUrl(imgUrl);
                paramsToShare.setText(content);
                break;
            case R.id.shareToQzone:
                platformStr = QZone.NAME;
                paramsToShare.setTitle(title);
                paramsToShare.setTitleUrl(url);
                paramsToShare.setText(content);
                paramsToShare.setImagePath(imgUrl);
                paramsToShare.setImageUrl(imgUrl);
                paramsToShare.setSite(title);
                paramsToShare.setSiteUrl(url);
                break;
            default:
                return;

        }

        Platform platform = ShareSDK.getPlatform(platformStr);
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                toast("分享成功!");
                shared = true;
                discountLayout.setVisibility(View.VISIBLE);
                discountTextView.setText("-" + getPriceStr(getSharedDiscount()));
                updateTotalPrice();
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                toast("分享失败!" + throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {
                toast("分享取消!");
            }
        });
        platform.share(paramsToShare);
    }

    @OnClick(R.id.operateButton)
    protected void onPayClicked() {
        if (!MyApp.hasLogin()) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }

        final String goodId = this.goodDetailsBean.getGoods_id();
        final int num = 1;
        final int isInstalled = installCheckBox.isOpened() ? 1 : 0;

        final String address = this.addressTextView.getText()
                .toString();
        if (selectDistrictBean == null || TextUtils.isEmpty(address)) {
            toast("请您填写完整收货地址!");
            return;
        }

        final String consignee = this.userTextView.getText()
                .toString();
        if (TextUtils.isEmpty(consignee)) {
            toast("请您填写完整收货人信息!");
            return;
        }

        final String phone = this.mobileTextView.getText()
                .toString();
        if (TextUtils.isEmpty(phone) || phone.length() != 11) {
            toast("请您填写11位的手机号码!");
            return;
        }

        final String province = selectDistrictBean.getProvince();
        final String city = selectDistrictBean.getCity();
        final String county = selectDistrictBean.getCounty();
        final String install_fee = String.valueOf(getInstallFee());
        final String added_fee = String.valueOf(getAddedFee());
        final String discount_amount = String.valueOf(getSharedDiscount());

        PayMethodDialog dialog = new PayMethodDialog(this);
        if (dialog.doModal() != AlertDialog.BUTTON_POSITIVE) {
            return;
        }

        showSmartLoadingDialog();
        final int pay_type = dialog.choice;
        HttpUtils.getHttpApi()
                .createOrder(MyApp.getUserToken(), goodId, num, isInstalled, province, city, county, address, consignee, phone, install_fee, added_fee, discount_amount, pay_type, "")
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        try {
                            dismissSmartLoadingDialog();
                            JSONObject result = new JSONObject(response.body());
                            if (result == null || !(result.opt("data") instanceof JSONObject)) {
                                toast("创建订单失败, 请稍后再试!");
                                return;
                            }

                            if (pay_type == 1) {
                                callWeiXinPay((JSONObject) result.opt("data"));
                            }
                            else {
                                callAliPay((JSONObject) result.opt("data"));
                            }

                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        dismissSmartLoadingDialog();
                        toast("创建订单失败, 请稍后再试!");
                    }
                });
    }

    private void callAliPay(JSONObject result) {
        this.orderNo = JSONUtil.getStringRecursive(result, "order_id");
        payAli(JSONUtil.getDoubleRecursive(result, "total_amount"), JSONUtil.getStringRecursive(result, "subject"), JSONUtil.getStringRecursive(result, "order_sn"));
    }

    private void callWeiXinPay(JSONObject result) {
        if (result != null) {
            try {
                this.orderNo = JSONUtil.getStringRecursive(result, "order_id");
                result.put("partnerid", result.optString("mch_id"));
                result.put("prepayid", result.optString("prepay_id"));
                result.put("noncestr", result.optString("nonce_str"));
                result.put("package", "Sign=WXPay");

                payWechat(result);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static String getPriceStr(float val) {
        return String.format("¥%.2f", val);
    }

    @Override
    protected void initLogic() {

    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        this.goodDetailsBean = (GoodDetailsBean) extras.getSerializable(GOODS_BEAN_KEY);
    }

    @Override
    public void paySuccess() {
        toast("购买成功");
        if (!TextUtils.isEmpty(this.orderNo)) {
            Intent intent = new Intent(OrderConfirmActivity.this, OrderDetailsActivity.class);
            intent.putExtra(OrderDetailsActivity.ORDER_ID, this.orderNo);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void payFail() {
        toast("购买失败或取消");
    }

    /**
     * 隐藏当前页面的软键盘
     */
    public void hideCurrentSoftInputMethod() {
        try {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void showSmartLoadingDialog() {
        if (dialogCount++ == 0) {
            showLoadingDialog();
        }
    }

    protected void dismissSmartLoadingDialog() {
        if (--dialogCount <= 0) {
            dissmissLoadingDialog();
            dialogCount = Math.max(0, dialogCount);
        }
    }
}
